﻿using System;
using System.IO;

namespace Hxsoft
{
	/// <summary>
	/// 流扩展类。
	/// </summary>
	public static class StreamExtensions
	{
		/// <summary>
		/// 将流转换成为 byte 数组。
		/// </summary>
		/// <param name="o">进行转换的流。</param>
		/// <returns>转换成的 byte 数组。</returns>
		public static byte[] ToBytes(this Stream o)
		{
			Stream fileContent = o;
			if ((fileContent == null) || (fileContent == Stream.Null))
			{
				return new byte[0];
			}

			MemoryStream mContent = ToMemoryStream(fileContent);
			if (mContent != null)
				return mContent.GetBuffer();
			return new byte[0];
		}

		public static MemoryStream ToMemoryStream(this Stream o)
		{
			if (o == null)
				return null;

			MemoryStream mo = o as MemoryStream;
			if (mo != null)
				return mo;

			mo = new MemoryStream();
			byte[] buffer = new byte[4096];

			int count = 0;
			do
			{
				count = o.Read(buffer, 0, buffer.Length);
				mo.Write(buffer, 0, count);

			} while (count != 0);

			return mo;
		}
	}
}